using System;
using System.Collections.Generic;
using UnityEngine;

namespace Voodoo.Analytics
{
	public class GlobalContext
	{
		[Serializable]
		internal struct CachedKeys
		{
			public List<string> keys;
		}

		private readonly Dictionary<string, string> _parameters;

		private const string K_PREFS_CACHED_PARAMETERS = "GlobalContext_CachedParameters";

		private const string K_PREFS_CACHED_PARAMETERS_KEY = "GlobalContext_CachedParameters_Key_{0}";

		public GlobalContext()
		{
			_parameters = new Dictionary<string, string>();
			foreach (KeyValuePair<string, string> cachedParameter in GetCachedParameters())
			{
				_parameters.Add(cachedParameter.Key, cachedParameter.Value);
			}
		}

		public Dictionary<string, string> GetParameters()
		{
			return _parameters;
		}

		public void Add(string key, string value, bool cached)
		{
			if (!_parameters.ContainsKey(key))
			{
				_parameters.Add(key, value);
			}
			else
			{
				_parameters[key] = value;
			}
			if (cached)
			{
				AddParameterToCache(key, value);
			}
		}

		private void AddParameterToCache(string key, string value)
		{
			CachedKeys cachedKeys = GetCachedKeys();
			cachedKeys.keys.Add(key);
			NintendoPlayerPrefs.SetString("GlobalContext_CachedParameters", JsonUtility.ToJson(cachedKeys));
			SetCachedValue(key, value);
			NintendoPlayerPrefs.Save();
		}

		private CachedKeys GetCachedKeys()
		{
			string @string = NintendoPlayerPrefs.GetString("GlobalContext_CachedParameters", "");
			CachedKeys result = default(CachedKeys);
			if (!string.IsNullOrEmpty(@string))
			{
				return JsonUtility.FromJson<CachedKeys>(@string);
			}
			result.keys = new List<string>();
			return result;
		}

		private Dictionary<string, string> GetCachedParameters()
		{
			CachedKeys cachedKeys = GetCachedKeys();
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			foreach (string key in cachedKeys.keys)
			{
				string cachedValue = GetCachedValue(key);
				if (!string.IsNullOrEmpty(cachedValue))
				{
					if (!dictionary.ContainsKey(key))
					{
						dictionary.Add(key, cachedValue);
					}
					else
					{
						dictionary[key] = cachedValue;
					}
				}
			}
			return dictionary;
		}

		private string GetPrefsKey(string key)
		{
			return $"GlobalContext_CachedParameters_Key_{key}";
		}

		public string GetCachedValue(string key)
		{
			return NintendoPlayerPrefs.GetString(GetPrefsKey(key), "");
		}

		private void SetCachedValue(string key, string value)
		{
			NintendoPlayerPrefs.SetString(GetPrefsKey(key), value);
			NintendoPlayerPrefs.Save();
		}

		public void DeleteAllCachedValues()
		{
			foreach (string key in GetCachedKeys().keys)
			{
				NintendoPlayerPrefs.DeleteKey(GetPrefsKey(key));
			}
			NintendoPlayerPrefs.DeleteKey("GlobalContext_CachedParameters");
		}
	}
}
